
import sys, os, cv2, time, gc, string

import math

from ctypes import *

dll = cdll.LoadLibrary('../build/unreDec.so');
#=================================================
splitMp4C = dll.splitMp4C
splitMp4C.restype = c_int
splitMp4C.argtypes = [c_char_p,c_char_p,c_int] 
#=================================================

def pyStr2C(pyStr):
    slen=len(pyStr)
    if slen>255:
        print("error! path length longer than 255!")
        exit(0)
    return (c_char * 256)(*bytes(pyStr, 'utf-8'))

def get_frame_count(path):
    totalframe=-1
    cap=cv2.VideoCapture(path)
    if cap.isOpened():
        totalframe = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        cap.release()
    return totalframe

def split_mp4(path, nSeg):
    if nSeg<2:
        raise Exception('nSeg={}<2'.format(nSeg))        
    t0=time.time()    
    name, ext=os.path.splitext(path)
    outtpl=name+'_%d'+ext
    retN=splitMp4C(pyStr2C(path),pyStr2C(outtpl),nSeg)    
    print('retN=',retN)
    print('time='+str(time.time()-t0))
    t0=time.time()    
    tt=0
    ret=[]
    for i in range(retN):
        cpath=name+'_'+str(i)+ext
        totalframe = get_frame_count(cpath)
        # print('totalframe=',totalframe)
        if totalframe>0:
            ret.append([cpath, tt])
        else:
            if os.path.exists(cpath):
                os.remove(cpath)        
        tt+=totalframe
    print('tt=',tt)
    totalframe0 = get_frame_count(path)
    print('totalframe0=',totalframe0)
    print('time='+str(time.time()-t0))
    return ret, tt


if __name__=='__main__':
    path="/home/u/20200702/HD_video1.mp4"
    path="0.mp4"
    path="3a.mp4"

    print(str(split_mp4(path, 4)))
    # print(get_frame_count(path))